let { addEnterprise, addOperateLog } = require("../../../api/programs/add");
let {
  insertNewProject,
  insertContacts,
} = require("../../../api/programs/follow");

let { getEnterprise } = require("../../../api/programs/Detail");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    xmfl: "",
    minDate: new Date("2000,01,01").getTime(),
    JGMC: {
      jglb: "",
      fwsname: "",
      fwsbh: "",
      sfrzqy: "",
    },
    JGLX: {
      fwsname: "",
      fwsbh: "",
      fwrname: "",
      rybh: "",
      phone: "",
    },
    xmbh: "",
    maxData: new Date().getTime(),

    enterprise: {
      xmbh: "", //项目编号
      qymc: "", //企业名称
      khbh: "", //企业编号
      zczb: "", //注册资本
      clsj: "", //成立时间
      zcdz: "", //注册地址
      qyfr: "", //法人代表
      hyfla: "", //一级行业分类
      hyflb: "", //二级行业分类
      // lxr: "", //联系人
      // lxphone: "", //手机号码
      // lxphone2: "", //其他联系方式
      nys: "", //年营收(万元)
      nss: "", //年税收(万元)
      zyyw: "", //主营业务
      ygrs: "", //员工人数
      xcdlx: "", //现有场地类型
      xmj: "", //现有场地面积
      zycp: "", //主营产品
      qyzz: "", //资质
      zysc: "", //主要市场区域
      qysb: "", //社保情况
      qtbz: "", //其他信息
      hxtd: "", //核心团队
      jsys: "", //技术优势
      nld: "", //拟落地业务或产品
      jgdmh: "", //信用代码
    }, //企业信息
    // 行业分类
    showHyfl: false,
    hyflOptions: [
      {
        code: "1",
        name: "环保",
        child: [
          {
            code: "01",
            name: "环境污染防治和处理设备",
          },
          {
            code: "02",
            name: "环境污染药剂和材料",
          },
          {
            code: "03",
            name: "环境监测仪器设备",
          },
          {
            code: "04",
            name: "环保工程勘察设计与施工",
          },
          {
            code: "05",
            name: "环境评估与检测服务",
          },
          {
            code: "06",
            name: "生态环境保护及污染治理服务",
          },
          {
            code: "07",
            name: "环保技术研发与技术服务",
          },
          {
            code: "08",
            name: "其他环保",
          },
        ],
      },
      {
        code: "2",
        name: "新能源",
        child: [
          {
            code: "09",
            name: "太阳能",
          },
          {
            code: "10",
            name: "风能",
          },
          {
            code: "11",
            name: "氢能",
          },
          {
            code: "12",
            name: "储能",
          },
          {
            code: "13",
            name: "智能电网",
          },
          {
            code: "14",
            name: "其他新能源",
          },
        ],
      },
      {
        code: "3",
        name: "大健康",
        child: [
          {
            code: "15",
            name: "生物技术",
          },
          {
            code: "16",
            name: "体外诊断",
          },
          {
            code: "17",
            name: "医疗机器人",
          },
          {
            code: "18",
            name: "康复辅具",
          },
          {
            code: "19",
            name: "植介入器械",
          },
          {
            code: "20",
            name: "低值耗材",
          },
          {
            code: "21",
            name: "医疗设备",
          },
          {
            code: "22",
            name: "医疗器械销售",
          },
          {
            code: "23",
            name: "其他大健康",
          },
        ],
      },
      {
        code: "4",
        name: "其他产业",
        child: [
          {
            code: "24",
            name: "其他产业",
          },
        ],
      },
    ],
    showDialog: false,

    fieldNames: {
      text: "name",
      value: "code",
      children: "child",
    },
    hyflValue: "",
    cascaderHyfl: "",
    // 时间
    showClsj: false,
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      return value;
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let timestamp = Date.parse(new Date());
    let date = new Date(timestamp);
    //获取年份
    let Y = date.getFullYear();
    //获取月份
    let M =
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1;

    let rand = "";
    for (let i = 0; i < 3; i++) {
      let r = Math.floor(Math.random() * 10);
      rand += r;
    }
    this.setData({
      "enterprise.xmbh": options.xmbh,
      "enterprise.khbh":
        options.khbh && options.khbh != "null"
          ? options.khbh
          : `khbh${Y}${M}${rand}`,
      "enterprise.sfrzqy": "0",
      bm: options.bm,
      tname: options.tname,
      xmmc: options.xmmc,
      xmbh: options.xmbh,

      xmfl: options.xmfl,
    });
    options.zfqID === null ||
    options.zfqID === "" ||
    options.zfqID === undefined
      ? null
      : this.getEnterprise();
  },
  getEnterprise() {
    getEnterprise(this.data.enterprise.khbh).then((res) => {
      let newData = {
        ...this.data.enterprise,
      };
      let getData = {
        ...res.data[0],
      };
      this.setData({
        enterprise: {
          ...newData,
          ...res.data[0],
        },
      });
      if (this.data.enterprise.hyflb != "") {
        let v;

        this.data.hyflOptions.forEach((item) => {
          return item.child.map((value) => {
            if (value.name == this.data.enterprise.hyflb) {
              v = value;
              return value;
            }
          });
        });
        let XZTIME = "";
        if (this.data.enterprise.clsj != "") {
          XZTIME = new Date(this.data.enterprise.clsj).getTime();
        } else {
          XZTIME = new Date().getTime();
        }
        this.setData({
          cascaderHyfl: v.code,
          hyflValue: `${getData.hyfla}/${getData.hyflb}`,
          currentDate: XZTIME,
        });
      }
    });
  },
  onPush() {
    try {
      let JyText;
      if (this.data.xmfl === "载体项目" || this.data.xmfl === "测试项目") {
        JyText = {
          qymc: "",
          hyfla: "",
          hyflb: "",
          zyyw: "",
          nss: "",
        };
      } else if (
        this.data.xmfl === "产业项目" ||
        this.data.xmfl === "测试项目"
      ) {
        JyText = {
          qymc: "",
          hyfla: "",
          hyflb: "",
          zyyw: "",
          nss: "",
          zyyw: "",
          nss: "",
          hyfla: "",
          hyflb: "",
          qyzz: "",
          nld: "",
        };
      } else if (
        this.data.xmfl === "政策项目" ||
        this.data.xmfl === "测试项目"
      ) {
        JyText = {
          qymc: "",
          hyfla: "",
          hyflb: "",
          zyyw: "",

          nss: "",
        };
      } else if (
        this.data.xmfl === "科技项目" ||
        this.data.xmfl === "测试项目"
      ) {
        JyText = {
          qymc: "",
          hyfla: "",
          hyflb: "",
          zyyw: "",
          nss: "",
          qyzz: "",
          jsys: "",
        };
      }

      for (const key in JyText) {
        if (this.data.enterprise[key] === "") {
          wx.showToast({
            title: "请填写必填项",
            icon: "error",
            duration: 2000, //持续的时间
          });
          return;
        }
      }

      if (this.data.xmfl == "人才项目") {
        let TEXTRC = {
          qymc: "",
          jgdmh: "",
          hyfla: "",
          hyflb: "",
          zczb: "",
          clsj: "",
          zcdz: "",
          qyfr: "",
          nys: "",
          nss: "",
          xcdlx: "",
          xmj: "",
          qtbz: "",
          zyyw: "",
          nss: "",
        };
        let requiredIS = true;
        for (const key in TEXTRC) {
          if (this.data.enterprise[key] !== "") {
            requiredIS = false;
          }
        }
        if (requiredIS) {
          // let pages = getCurrentPages();
          // let prevPage = pages[pages.length - 2];
          wx.navigateBack({
            delta: -1,
            // success: function (e) {
            //   // 成功的回调
            //   if (prevPage == undefined || prevPage == null) return;
            //   prevPage.getDetail(); // 调用A页面的方法, 并将值传过去
            // },
          });
          return;
        }
      }

      const regexxy = /^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/;
      const regexphone = /^(1[3-9]\d{9}|\d{3,4}-\d{7,8})$/;
      // if (!regexxy.test(this.data.enterprise.jgdmh)) {
      //   return wx.showToast({
      //     title: "信用代码格式错误",
      //     icon: "none",
      //     duration: 2000, //持续的时间
      //   });
      // }
      // if (this.data.enterprise.lxphone&&!regexphone.test(this.data.enterprise.lxphone)) {
      //   return wx.showToast({
      //     title: "手机号码格式错误",
      //     icon: "none",
      //     duration: 2000, //持续的时间
      //   });
      // }
      this.addEnterprise();
    } catch (error) {
      console.log(error);
    }
  },
  addEnterprise() {
    let timestamp = new Date().getTime();
    let dateOne = new Date(timestamp);
    //获取年份
    let Y = dateOne.getFullYear();
    //获取月份
    let M =
      dateOne.getMonth() + 1 < 10
        ? "0" + (dateOne.getMonth() + 1)
        : dateOne.getMonth() + 1;

    let rand = "";
    for (let i = 0; i < 3; i++) {
      let r = Math.floor(Math.random() * 10);
      rand += r;
    }
    if (this.data.enterprise.zfqID) {
      this.setData({
        "JGMC.zfqID": this.data.enterprise.zfqID,
      });
    }
    this.setData({
      "JGMC.sfrzqy": this.data.enterprise.sfrzqy,
      "JGMC.fwsname": this.data.enterprise.qymc,
      "JGMC.fwsbh": this.data.enterprise.khbh,
      "JGMC.jglb": "企业组织",
      "JGMC.xmbh": this.data.xmbh,
      "JGMC.fwlb": "",
      "JGMC.jgdmh": this.data.enterprise.jgdmh,

      JGLX: {
        fwsname: this.data.enterprise.qymc,
        fwsbh: this.data.enterprise.khbh,
        fwrname: this.data.enterprise.lxr,
        rybh: `fwsr${Y}${M}${rand}`,
        phone: this.data.enterprise.lxphone,
        xmbh: this.data.enterprise.xmbh,
      },
    });
    let time = new Date().getTime();
    //将时间戳格式转换成年月日时分秒
    let date = new Date(time);
    let bbTime = `${date.getFullYear()}-${
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1
    }-${date.getDate() < 10 ? "0" + date.getDate() : date.getDate()}`;
    let tjTime = `${
      date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
    }:${date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()}:${
      date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
    }`;
    for (const key in this.data.enterprise) {
      if (
        this.data.enterprise[key] === null ||
        this.data.enterprise[key] === "null"
      ) {
        let param = `enterprise.${key}`;
        this.setData({
          [param]: "",
        });
      }
    }
    let enterpriseInfo = this.data.enterprise;
    addEnterprise(enterpriseInfo).then((res) => {
      wx.showToast({
        title: "企业信息填报完成",
        icon: "none",
      });

      insertNewProject(this.data.JGMC);
      // insertContacts(this.data.JGLX)

      addOperateLog({
        type: 2,
        khbh: this.data.enterprise.khbh,
        xmbh: this.data.enterprise.xmbh,
        xmmc: this.data.xmmc,
        bm: this.data.bm,
        tname: this.data.tname,
        tjsj: `${bbTime} ${tjTime}`,
      });
      setTimeout(() => {
        this.setData({
          showDialog: true,
        });
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        wx.navigateBack({
          delta: -1,
          success: function (e) {
            // 成功的回调
            if (prevPage == undefined || prevPage == null) return;
            prevPage.getDetail(); // 调用A页面的方法, 并将值传过去
          },
        });
      }, 1000);
    });
  },
  onInputTime(e) {
    this.setData({
      currentDate: e.detail,
    });
  },

  inputValue(e) {
    let param = e.currentTarget.dataset.name; //字段名
    let value = e.detail; //值

    let key = `enterprise.${param}`;
    // const msg=`checkData.${param}`;

    this.setData({
      [key]: value,
      // [msg]:'' //清空错误提示
    });
  },
  // 格式化时间
  formatterTime(time) {
    let date = new Date(time);
    let year = date.getFullYear();
    let month = ("0" + (date.getMonth() + 1)).slice(-2);
    let day = ("0" + date.getDate()).slice(-2);
    let hours = ("0" + date.getHours()).slice(-2);
    let minutes = ("0" + date.getMinutes()).slice(-2);
    let seconds = ("0" + date.getSeconds()).slice(-2);
    let formattedTime = year + "-" + month + "-" + day;
    return formattedTime;
  },
  onconfirmTime() {
    let Time = this.formatterTime(this.data.currentDate);
    this.setData({
      "enterprise.clsj": Time,
    });
    this.setData({
      showHyfl: false,
      showClsj: false,
    });
  },
  onconfirm() {
    this.setData({
      showHyfl: false,
      showClsj: false,
    });
  },
  // onChange(event) {
  //   this.setData({
  //     "enterprise.rzxt": event.detail,
  //   });
  // },
  onClickClsj(e) {
    this.setData({
      showClsj: true,
    });
  },
  onClickHyfl(e) {
    this.setData({
      showHyfl: true,
    });
  },

  onClose() {
    this.setData({
      showHyfl: false,
      showClsj: false,
    });
  },
  onChangeHyfl(e) {},
  onFinishHyfl(e) {
    const { selectedOptions, value } = e.detail;

    const hyflValue = selectedOptions
      .map((option) => option.text || option.name)
      .join("/");

    this.setData({
      hyflValue,
      cascaderHyfl: value,
      "enterprise.hyfla": selectedOptions[0].name,
      "enterprise.hyflb": selectedOptions[1].name,
    });
    this.onClose();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
